package org.wangchaocheng.cloudgallery.user.executor.command;

import java.util.List;

import lombok.RequiredArgsConstructor;
import org.springframework.transaction.annotation.Transactional;
import org.wangchaocheng.cloudgallery.common.annotation.CommandExecutor;
import org.wangchaocheng.cloudgallery.commond.user.UserRoleSaveCmd;
import org.wangchaocheng.cloudgallery.dto.user.UserRoleDTO;
import org.wangchaocheng.cloudgallery.user.assembler.UserRoleAssembler;
import org.wangchaocheng.cloudgallery.user.gateway.UserRoleGateway;

/**
 * 用户角色保存执行器
 *
 * @author wangchaocheng
 * @date 2025/04/08
 */
@CommandExecutor
@RequiredArgsConstructor
public class UserRoleSaveCmdExe {

    private final UserRoleGateway userRoleGateway;

    @Transactional(rollbackFor = Exception.class)
    public void execute(UserRoleSaveCmd cmd) {
        // 1. 先清空用户的角色绑定关系
        userRoleGateway.removeByUserId(cmd.getUserId());
        // 2. 重新绑定用户角色
        List<UserRoleDTO> userRoleList = UserRoleAssembler.INSTANCE.assembleList(cmd);
        userRoleGateway.batchSave(userRoleList);
    }
}
